﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using BusinessServices;
using BusinessServices.Enumerates;
using Core.Utilities;
using DataEntities;

namespace CarLeaseManageSystem
{
    public partial class FormClientMana : Form
    {
        //客户注册信息是否填写完整
        bool bKHInfo = false;

        //缓存已加载客户
        List<KeHuInfo> _keHuInfoCache = new List<KeHuInfo>();

        private readonly KeHuService _keHuService;
        private readonly ChuZuService _chuZuService;
        private readonly YuZuService _yuZuService;
        private readonly WeiZhangService _weiZhangService;

        public FormClientMana()
        {
            _keHuService = new KeHuService();
            _chuZuService = new ChuZuService();
            _yuZuService = new YuZuService();
            _weiZhangService = new WeiZhangService();
            InitializeComponent();
        }

        //窗口初使化
        private void FormClientMana_Load(object sender, EventArgs e)
        {
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedTab == tabExistClient)
            {
                LoadListView(KeHuStatus.All);
                return;
            }
            btnReset_Click(null, e);//清除表单数据   
        }

        private void ShowKeHuDetail(int keHuId)
        {
            var keHuInfo = _keHuInfoCache.First(p => p.iKeHuId == keHuId);
            txtBoxName.Text = keHuInfo.sName;
            comBoxSex.Text = keHuInfo.bSex ? "男" : "女";
            txtBoxIdCard.Text = keHuInfo.sIdCard;
            txtBoxDriveId.Text = keHuInfo.sDriveId;
            comBoxBlack.Text = keHuInfo.bBlackList ? "是" : "否";
            dateRegister.Text = keHuInfo.tRegiDate.ToString();
            comBoxOut.Text = keHuInfo.bLogout ? "是" : "否";
            dateLogout.Text = keHuInfo.tLogoutDate.ToString();
            btnEdit.Tag = keHuId;
            pictBoxPhoto.Image = keHuInfo.mPhoto.ToImage();

            var cz = _chuZuService.GetSimpleChuZuInfoByKeHuId(keHuId);
            var yz = _yuZuService.GetSimpleYuZuInfoByKeHuId(keHuId);
            var wz = _weiZhangService.GetSimpleWeiZhangInfoByKeHuId(keHuId);

            txtBoxLeaseInfo.Text = cz.Content + yz.Content;
            txtBoxWZ.Text = wz.Content;
            labLeased.Text = string.Format("出租[{0}]条 预租[{1}]条", cz.Count, yz.Count);
            labWZ.Text = String.Format("共[{0}]条 未处理[{1}]条", wz.Count, wz.Unsettled);
        }

        // 为列表视图加载数据
        private void LoadListView(KeHuStatus status)
        {
            _keHuInfoCache = _keHuService.GetAll(status);

            listViewExist.Items.Clear();
            foreach (KeHuInfo keHu in _keHuInfoCache)
            {
                ListViewItem item = new ListViewItem();
                item.Text = keHu.sName;
                item.Tag = keHu.iKeHuId;
                item.SubItems.Add(keHu.sIdCard);
                item.SubItems.Add(keHu.bLogout.ToString());
                listViewExist.Items.Add(item);
            }
            if (listViewExist.Items.Count > 0)
            {
                listViewExist.Items[0].Selected = true;
            }
        }

        //新建客户信息        
        private void btnNewSave_Click(object sender, EventArgs e)
        {

            if (txtBoxNewName.Text == "" || txtBoxNewDriveId.Text == "" || txtBoxNewIdCard.Text == "")
            {
                MessageBox.Show("请将信息填写完整！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                bKHInfo = false;
                return;
            }

            if (txtBoxNewDriveId.Text.Length < 18)
            {
                txtBoxNewDriveId.Text = txtBoxNewDriveId.Text + "   ";
            }

            if (txtBoxNewDriveId.Text.Length != 18 || txtBoxNewIdCard.Text.Length != 18)
            {
                MessageBox.Show("有证件号码位数不对！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtBoxNewDriveId.Text = txtBoxNewDriveId.Text.Trim();
                bKHInfo = false;
                return;
            }

            var isExisted = _keHuService.IsExisted(txtBoxNewIdCard.Text);

            //如果该客户已经存在,则不保存并返回
            if (isExisted)
            {
                MessageBox.Show("已存在与该身份证号码相同的客户信息！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            //将图片写入缓冲区
            byte[] upLoadBuff = pictBoxNewPhoto.Image.ToBinary();

            var newUser = new KeHuInfo
            {
                sName = txtBoxNewName.Text,
                bSex = (comBoxNSex.Text == "男" ? true : false),
                sIdCard = txtBoxNewIdCard.Text,
                sDriveId = txtBoxNewDriveId.Text,
                tRegiDate = dateNewRegi.Value,
                tLogoutDate = DateTime.Now,
                mPhoto = upLoadBuff
            };

            _keHuService.Add(newUser);

            bKHInfo = true;

            var dResult = MessageBox.Show("新用户添加成功，是否继续？", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
            if (dResult == DialogResult.No)
            {
                tabControl1.SelectTab(tabExistClient);
            }
        }

        //当选中列表视图中的某项时
        private void listViewExist_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if(!e.IsSelected)
            {
                return;
            }
            var keHuId = (int)e.Item.Tag;
            ShowKeHuDetail(keHuId);
        }

        //上传图片
        private void btnUpLoad_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "jpg格式文件|*.jpg|bmp格式文件|*.bmp|gif格式文件|*.gif";

            //打开对话框，选择要上传的照片
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                //获取图片,并存为BMP格式
                Bitmap bmp = (Bitmap)Image.FromFile(openFileDialog1.FileName);

                //更改图片大小
                pictBoxNewPhoto.Image = bmp.Resize(pictBoxNewPhoto.Width, pictBoxNewPhoto.Height);
            }
            //如果没有选择照片就加载默认照片
            else
            {
                pictBoxNewPhoto.Image = Properties.Resources.defaultZP;
            }
        }

        //重置
        private void btnReset_Click(object sender, EventArgs e)
        {
            txtBoxNewName.Text = "";
            txtBoxNewDriveId.Text = "";
            txtBoxNewIdCard.Text = "";
            pictBoxNewPhoto.Image = Properties.Resources.defaultZP;
            dateNewRegi.Value = DateTime.Now;
            comBoxNSex.Text = "男";
        }

        //现在去预租
        private void btnYZNow_Click(object sender, EventArgs e)
        {
            btnNewSave_Click(sender, e);
            if (!bKHInfo)
                return;
            int i = 0;
            foreach (Form cForm in MdiChildren)
            {
                if (cForm.Name == "FormYuZuMana")
                {
                    cForm.Focus();
                    break;
                }
                i++;
            }
            if (i == MdiChildren.Count())
            {
                FormYuZuMana yzForm = new FormYuZuMana();
                yzForm.MdiParent = this.MdiParent;
                yzForm.Show();
            }
            this.Close();//关闭当前窗口
        }
        //现在去租车
        private void btnCZNow_Click(object sender, EventArgs e)
        {
            btnNewSave_Click(sender, e);
            if (!bKHInfo)
                return;
            int i = 0;
            foreach (Form cForm in MdiChildren)
            {
                if (cForm.Name == "FormLeaseMana")
                {
                    cForm.Focus();
                    break;
                }
                i++;
            }
            if (i == MdiChildren.Count())
            {
                FormLeaseMana cForm = new FormLeaseMana();
                cForm.MdiParent = this.MdiParent;
                cForm.Show();
            }
            this.Close();//关闭当前窗口
        }

        private void comBoxArea_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (comBoxArea.SelectedIndex)
            {
                case 0:
                    LoadListView(KeHuStatus.IsLogout); break;
                case 1:
                    LoadListView(KeHuStatus.IsActive); break;
                default:
                    LoadListView(KeHuStatus.All); break;
            }
        }

        private void btnSear_Click(object sender, EventArgs e)
        {
            listViewExist.Items.Clear();
            _keHuInfoCache.FindAll(FilterKeHu);
        }

        private bool FilterKeHu(KeHuInfo keHu)
        {
            if (keHu.sName.Contains(txtBoxSearName.Text))
            {
                ListViewItem item = new ListViewItem();
                item.Text = keHu.sName;
                item.Tag = keHu.iKeHuId;
                item.SubItems.Add(keHu.sIdCard);
                item.SubItems.Add(keHu.bLogout.ToString());
                listViewExist.Items.Add(item);
                return true;
            }
            return false;
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            txtBoxName.ReadOnly = txtBoxIdCard.ReadOnly = txtBoxDriveId.ReadOnly = false;
            comBoxSex.Enabled = comBoxOut.Enabled = comBoxBlack.Enabled = dateLogout.Enabled = true;
            if (btnEdit.Text == "保存")
            {
                var keHuId = (int)btnEdit.Tag;
                _keHuService.Update(keHuId, UpdateKeHuInfo);

                txtBoxName.ReadOnly = txtBoxIdCard.ReadOnly = txtBoxDriveId.ReadOnly = true;
                comBoxSex.Enabled = comBoxOut.Enabled = comBoxBlack.Enabled = dateLogout.Enabled = false;
                btnEdit.Text = "编辑";

                comBoxArea_SelectedIndexChanged(sender, e);
                return;
            }
            btnEdit.Text = "保存";
        }

        //此委托更新客户信息
        private void UpdateKeHuInfo(KeHuInfo keHu)
        {
            keHu.sName = txtBoxName.Text;
            keHu.bSex = comBoxSex.Text == "男";
            keHu.sIdCard = txtBoxIdCard.Text;
            keHu.sDriveId = txtBoxDriveId.Text;
            keHu.tLogoutDate = dateLogout.Value;
            keHu.bBlackList = comBoxBlack.Text == "是";
            keHu.bLogout = comBoxOut.Text == "是";
        }

        private void txtBoxNewIdCard_TextChanged(object sender, EventArgs e)
        {
            labCLength.Text = "[" + txtBoxNewIdCard.Text.Length + "/18]";
            if (txtBoxNewIdCard.Text.Length > 18)
            {
                MessageBox.Show("标准身份证号码只有18位!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtBoxNewIdCard.Text = txtBoxNewIdCard.Text.Substring(0, 18);
                this.Controls.Find("txtBoxNewDriveId", true)[0].Focus();
            }
        }

        private void txtBoxNewIdCard_Leave(object sender, EventArgs e)
        {
            if (txtBoxNewIdCard.Text.Length < 18)
            {
                MessageBox.Show("请输入18位身份证号码!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtBoxNewIdCard.Focus();
            }

        }

        private void txtBoxNewDriveId_TextChanged(object sender, EventArgs e)
        {
            labDLength.Text = "[" + txtBoxNewDriveId.Text.Length + "/18]";
            if (txtBoxNewDriveId.Text.Length > 18)
            {
                MessageBox.Show("标准驾驶证号码只有15和18位!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtBoxNewDriveId.Text = txtBoxNewDriveId.Text.Substring(0, 18);
                this.Controls.Find("dateNewRegi", true)[0].Focus();
            }
        }

        private void txtBoxNewDriveId_Leave(object sender, EventArgs e)
        {
            if (txtBoxNewDriveId.Text.Length < 15)
            {
                MessageBox.Show("请输入标准15或18位驾驶证号码!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtBoxNewDriveId.Focus();
            }
            else
                if (txtBoxNewDriveId.Text.Length > 15 && txtBoxNewDriveId.Text.Length < 18)
                {
                    MessageBox.Show("请输入标准15或18位驾驶证号码!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtBoxNewDriveId.Focus();
                }
        }
    }
}
